package wang.hex.codetransfer.image;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Arrays;

/**
 * @Author wujie
 * @Class FileEncode
 * @Description
 * @Date 2021/1/26 15:46
 */
public class FileEncode {

    public static void encodeFile(String path, String target) {
        File file = new File(path);
        if (file.length() > Integer.MAX_VALUE - 256) {
            throw new RuntimeException("不支持过长的文件");
        }
        String absolutePath = file.getAbsolutePath().replaceAll(".*/(.*)", "$1");
        byte[] bytes1 = (absolutePath + "/").getBytes();
        byte[] bytes = new byte[bytes1.length + (int) file.length()];
        System.arraycopy(bytes1, 0, bytes, 0, bytes1.length);
        try (InputStream f = new FileInputStream(file)) {
            f.read(bytes, bytes1.length, (int) file.length());
        } catch (Exception e) {
            e.printStackTrace();
        }
        int ceil = (int) Math.ceil(Math.sqrt(bytes.length / 3.0 + 1));
        BufferedImage bufferedImage = ImageCreate.encodeToImage(bytes, ceil, ceil);


        try {
            ImageIO.write(bufferedImage, "png", new File(target));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void decodeFile(String path, String target) {
        try {
            BufferedImage read = ImageIO.read(new File(path));
            byte[] bytes = ImageCreate.decodeToByte(read);
            int splitIndex = -1;
            for (int i = 0; i < bytes.length; i++) {
                if (bytes[i] == 47) {
                    splitIndex = i;
                    break;
                }
            }
            String fileName = new String(Arrays.copyOfRange(bytes, 0, splitIndex));
            File file = new File(target);
            if (file.isDirectory()) {
                file = new File(file.getAbsolutePath() + "/" + fileName);
            }
            try (FileOutputStream out = new FileOutputStream(file)) {
                out.write(bytes, splitIndex, bytes.length - splitIndex);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

//    public static void main(String[] args) {
//        encodeFile("d:/pd.txt", "d:/1.png");
//        decodeFile("d:/1.png", "d:/pd1.txt");
//    }
}
